package net.bat.upload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bat.servlet.JSonBaseServlet;
import net.bat.util.Cfg;
import net.cs.um.UMService;
//import net.sf.json.JSONObject;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import dao.hb.UUser;

public class HtmlEditorUploadServlet extends uploadServlet{
	static Gson gson=new GsonBuilder().setPrettyPrinting().create();

	  static public void onSubmit(HttpServletRequest request, HttpServletResponse response) throws Exception{
		  	String path = Cfg.getRealRoot()+"/upload/";
		     request.setCharacterEncoding("UTF-8");
	         Map map1 = new HashMap();
			  //是否指定path
			 String fp = request.getParameter("fp");
			 //是否不需要自动命名
		     //String tid=request.getParameter("tid");
				 
		      boolean writeToFile = true;
		      response.setContentType(CONTENT_TYPE);
		      PrintWriter out = response.getWriter();
		      int total = request.getContentLength();
	    	  if(total > MAX_LEN){
	    		  map.put("success", false);
	    	      map.put("msg", "上传文件过大，上传失败！");
	    	      out.print(gson.toJson(map));
	    		  throw new IOException("file size must <"+MAX_LEN);
	    	  }
		      String msg = "OK";
//		    Check that we have a file upload request
		      boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		      if(!isMultipart) {
				return;
			}
		  UploadListener listener = new UploadListener(request,0);
		  // Create a factory for disk-based file items
		  DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
		  //DiskFileItemFactory  factory = new DiskFileItemFactory();
		  //factory.setSizeThreshold(1024);
		  ServletFileUpload upload = new ServletFileUpload(factory);
	      // 解析request
	      List items = upload.parseRequest(request);
			UUser usr = UMService.getUserBySession(request);
			Integer uid = usr.getId();

	      // 处理Item
	      Iterator iter = items.iterator();
	      while (iter.hasNext()) {
	          FileItem item = (FileItem) iter.next();
	          if (!item.isFormField()){//file
	        	   String fpath=item.getName();
	        		int pos = fpath.lastIndexOf(File.separatorChar);
	        		if(pos!=-1){
	        		   fpath=fpath.substring(pos+1);
	        		}
	               String fileName;
	               map1.put("fileName",fpath);
	               if(uid == null ){
	            	   map.put("success",false);
	         	       map.put("msg", "没有用户信息，请核查当前操作用户信息。");  
	         	       out.print(gson.toJson(map));
	        	      return;
	               }
	               fileName=  "_["+uid+"]"+fpath;
	               if (writeToFile) {
	                //保存到硬盘设定的目录
	            	File uploadedFile;
	            	if(fp==null){
		            	//String fnp=getFPath(fileName);
	            		String fnp=getFPath(fileName);
	                    map1.put("url", "/bat/upload/"+fnp.replace("\\", "/"));
		            	makeDir(fnp,path,true);
		                uploadedFile = new File(path +fnp);
	            	}else{
	            		uploadedFile = new File(fp +fileName);
	            	}
	                item.write(uploadedFile);

	               } else {
	                InputStream uploadedStream = item.getInputStream();
	                uploadedStream.close();
	               }
	          }
	      }
	      Map map = new HashMap();
	      map.put("success", true);
	      map.put("msg", msg);
	      map.put("data", map1);
	      // 转换成对象，不要转换成;  
	     // System.out.println(gson.toJson(map));
	      //out.print(JSonBaseServlet.toJSON(map));
	      out.print(gson.toJson(map));
	 }
	  @Override
	  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  	try {
		  		onSubmit(request,response);
		  	} catch (Exception e) {
		  		// TODO Auto-generated catch block
		  		e.printStackTrace();
		  	}
	    }
}
